document.addEventListener('DOMContentLoaded', function() {
    const username = localStorage.getItem('username');
    const role = localStorage.getItem('role');
    
    if (!username || role !== 'doctor') {
        window.location.href = 'index.html';
    }
    
    const planSimulationBtn = document.getElementById('planSimulationBtn');
    const dataAnalysisBtn = document.getElementById('dataAnalysisBtn');
    const pendingCallsBtn = document.getElementById('pendingCallsBtn');
    const logoutBtn = document.getElementById('logoutBtn');
    
    const planSimulationSection = document.getElementById('planSimulationSection');
    const dataAnalysisSection = document.getElementById('dataAnalysisSection');
    const pendingCallsSection = document.getElementById('pendingCallsSection');
    
    planSimulationBtn.addEventListener('click', function() {
        setActiveSection(planSimulationBtn, planSimulationSection);
    });
    
    dataAnalysisBtn.addEventListener('click', function() {
        setActiveSection(dataAnalysisBtn, dataAnalysisSection);
    });
    
    pendingCallsBtn.addEventListener('click', function() {
        setActiveSection(pendingCallsBtn, pendingCallsSection);
        loadCallsList();
    });
    
    logoutBtn.addEventListener('click', function() {
        localStorage.clear();
        window.location.href = 'index.html';
    });
    
    const planForm = document.getElementById('planForm');
    const evaluationResult = document.getElementById('evaluationResult');
    const resultItems = document.querySelector('.result-items');
    
    planForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const height = parseFloat(document.getElementById('patientHeight').value || 0) / 100;
        const weight = parseFloat(document.getElementById('patientWeight').value || 0);
        const bmi = height > 0 ? weight / (height * height) : 0;
        
        const mobility = parseInt(document.getElementById('mobility').value || 0);
        const nutrition = parseInt(document.getElementById('nutrition').value || 0);
        const moisture = parseInt(document.getElementById('moisture').value || 0);
        const pressureUlcerRisk = (10 - mobility) * 0.4 + (10 - nutrition) * 0.3 + moisture * 0.3;
        
        const age = parseInt(document.getElementById('patientAge').value || 0);
        const vision = parseInt(document.getElementById('vision').value || 0);
        const balance = parseInt(document.getElementById('balance').value || 0);
        const fallRisk = (age > 65) * 3 + (10 - vision) * 0.3 + (10 - balance) * 0.4;
        
        const bmiStatus = bmi >= 18.5 && bmi <= 24 ? '正常' : '异常';
        const pressureUlcerLevel = pressureUlcerRisk < 5 ? '低' : (pressureUlcerRisk < 8 ? '中' : '高');
        const fallRiskLevel = fallRisk < 4 ? '低' : (fallRisk < 7 ? '中' : '高');
        
        let overallStatus = '绿灯';
        if ((bmiStatus === '异常' || pressureUlcerRisk >= 5 || fallRisk >= 4) && !(pressureUlcerRisk >= 8 || fallRisk >= 7)) {
            overallStatus = '黄灯';
        } else if (pressureUlcerRisk >= 8 || fallRisk >= 7) {
            overallStatus = '红灯';
        }
        
        resultItems.innerHTML = `
            <div class="result-item">
                <strong>BMI:</strong> ${bmi.toFixed(1)} (${bmiStatus})
            </div>
            <div class="result-item">
                <strong>压疮风险:</strong> ${pressureUlcerRisk.toFixed(1)} (${pressureUlcerLevel})
            </div>
            <div class="result-item">
                <strong>跌倒风险:</strong> ${fallRisk.toFixed(1)} (${fallRiskLevel})
            </div>
            <div class="result-item">
                <strong>整体评估:</strong> <span style="color: ${overallStatus === '绿灯' ? 'green' : overallStatus === '黄灯' ? 'orange' : 'red'}">${overallStatus}</span>
            </div>
        `;
        
        evaluationResult.classList.remove('hidden');
    });
    
    const loadDataBtn = document.getElementById('loadDataBtn');
    const dataChart = document.getElementById('dataChart');
    const analysisSummary = document.getElementById('analysisSummary');
    
    loadDataBtn.addEventListener('click', function() {
        dataChart.innerHTML = '<p style="text-align: center; line-height: 400px;">数据加载中...</p>';
        
        setTimeout(() => {
            dataChart.innerHTML = '<p style="text-align: center; line-height: 400px;">患者数据可视化图表</p>';
            analysisSummary.innerHTML = '<p>数据分析摘要：患者生命体征基本稳定，偶有血压波动，建议继续观察并定期监测。</p>';
        }, 1000);
    });
    
    function setActiveSection(button, section) {
        document.querySelectorAll('.menu button').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.section').forEach(sec => sec.classList.add('hidden'));
        
        button.classList.add('active');
        section.classList.remove('hidden');
    }
    
    function loadCallsList() {
        const callsList = document.getElementById('callsList');
        callsList.innerHTML = `
            <div class="call-item">
                <div>
                    <strong>患者：</strong>患者1
                </div>
                <button>接入</button>
            </div>
            <div class="call-item">
                <div>
                    <strong>患者：</strong>患者2
                </div>
                <button>接入</button>
            </div>
        `;
        
        document.querySelectorAll('.call-item button').forEach(button => {
            button.addEventListener('click', function() {
                alert('已接入患者咨询');
            });
        });
    }
});
